package zhongbo.javaweb.instagram.web.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * 说明： 接口过滤器
 * 记录接口调用时间性能日志
 *
 * @author zhongboWork
 * @version 1.0
 * @since 2021-08-20 09:38
 */
@Component
@Slf4j
public class ControllerFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Date startTime = new Date();
        filterChain.doFilter(servletRequest, servletResponse);
        Date endTime = new Date();
        if (!HttpMethod.OPTIONS.name().equals(request.getMethod())) {
            log.info(request.getScheme() + "调用[" + request.getMethod() + "][" + request.getRemoteAddr() + "] " + request.getRequestURI() + "时间:" + (endTime.getTime() - startTime.getTime()) + "ms");
        }
    }

    @Override
    public void destroy() {

    }
}
